//
//  API_Gift.swift
//  WalkNovel
//
//  Created by Kevin on 2023/9/22.
//

import UIKit
import Moya

enum API_Gift {
    /// 礼物列表
    case giftList
    /// 赠送礼物
    case giveGift(String, String)
    /// 收到礼物列表
    case receiveGiftList(String, Int)
    /// 送出礼物列表
    case giveGiftList(Int)
    /// 排行榜礼物列表
    case rankGiftList(String, Int)
}

let gift_timeoutClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<API_Gift>.RequestResultClosure) in
    do {
        var request = try endpoint.urlRequest()
        request.timeoutInterval = 5
        done(.success(request))
    }catch {
        return
    }
}

let provider_gift = MoyaProvider<API_Gift>(requestClosure: gift_timeoutClosure)

extension API_Gift: TargetType {
    var baseURL: URL {
        return URL(string: server.APIHost)!
    }
    
    var path: String {
        switch self {
        case .giftList:
            return "/Giftmanage/getGiftList"
        case .giveGift(_, _):
            return "/Giftmanage/giveSb"
        case .receiveGiftList(_, _):
            return "/Giftmanage/getBookGift"
        case .giveGiftList(_):
            return "/Giftmanage/getUserGift"
        case .rankGiftList(_, _):
            return "/Article/rank"
        }
    }
    
    var method: Moya.Method {
        return .post
    }
    
    var parameterEncoding: ParameterEncoding {
        return JSONEncoding.default
    }
    
    var sampleData: Data {
        return "test".data(using: String.Encoding.utf8)!
    }
    
    var task: Task {
        var ps: [String: Any] = ["ver": getAPPVersion(), "channel": "ios", "third_channel": "apple", "timestamp": Date().timeStamp, "userId": getUser()?.userId ?? "", "uuid": getKeyUUId(), "user_channel": getADID()]
        switch self {
        case .giftList:
            break
        case .giveGift(let bookId, let giftId):
            ps["bookId"] = bookId
            ps["giftNo"] = giftId
        case .receiveGiftList(let bookId, let page):
            ps["bookId"] = bookId
            ps["page"] = page
            ps["num"] = 10
        case .giveGiftList(let page):
            ps["page"] = page
            ps["num"] = 10
        case .rankGiftList(let type, let page):
            ps["type"] = type
            ps["page"] = page
            ps["num"] = 10
        }
        return .requestParameters(parameters: ps, encoding: JSONEncoding.default)
    }
    
    var headers: [String : String]? {
        return ["content-type": "application/json; charset=UTF-8"]
    }
}
